<template>
  <!-- 物料主数据表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1300px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <!-- 第一行 -->
      <el-divider content-position="left" v-if="!props.isReadonly"
        ><span style="font-weight: bold; font-size: 16px"
          >基本信息</span
        ></el-divider
      >
      <el-row>
        <el-col :span="6">
          <el-form-item label="存货编码" prop="materialCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.materialCode"
              placeholder="请输入存货编码"
              clearable
            />

            <span class="word" v-else>{{ formData.materialCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料名称" prop="materialName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.materialName"
              placeholder="请输入物料名称"
              clearable
            />

            <span class="word" v-else>{{ formData.materialName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="短号" prop="shortCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.shortCode"
              placeholder="请输入短号"
              clearable
            />
            <span class="word" v-else>{{ formData.shortCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="外来编号" prop="srcCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.srcCode"
              placeholder="请输入外来编号"
              clearable
            />

            <span class="word" v-else>{{ formData.srcCode }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="工厂" prop="plantCode">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.plantCode"
              placeholder="请选择工厂"
              clearable
              @change="changePlant"
              filterable
            >
              <el-option
                v-for="item in plantList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.organizationCode"
              />
            </el-select>

            <span v-else>{{ formData.plantCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料组" prop="materialGroupId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.materialGroupId"
              placeholder="请选择物料组"
              clearable
              @change="changeMaterialGroup(formData.materialGroupId)"
              filterable
            >
              <el-option
                v-for="item in mdmmatgroup"
                :key="item.id"
                :label="item.materialGroupName"
                :value="item.id"
              />
            </el-select>

            <span class="word" v-else>{{ materialGroup }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料类型" prop="materialType">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.materialType"
              placeholder="请选择物料类型"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('MaterialType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("MaterialType", formData.materialType)
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料分类" prop="materialClassification">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.materialClassification"
              placeholder="请选择物料分类"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'MaterialClassify'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("MaterialClassify", formData.materialClassification)
            }}</span>
          </el-form-item>
        </el-col>
        <!--<el-col :span="6">
          <el-form-item label="物料状态" prop="materialState">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.materialState"
              placeholder="请选择物料状态"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('MaterialState')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("MaterialState", formData.materialState)
            }}</span>
          </el-form-item>
        </el-col>-->
      </el-row>
      <!-- 第三行 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="计量单位" prop="unit">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.unit"
              placeholder="请选择计量单位"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'MeasurementUnit'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{
              useDictionary("MeasurementUnit", formData.unit)
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="图号" prop="figureNumber">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.figureNumber"
              placeholder="请输入图号"
              clearable
            />
            <span class="word" v-else>{{ formData.figureNumber }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否可炉尾" prop="isTail">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.isTail"
              placeholder="请选择是否可炉尾"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('YesNo')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName("YesNo", formData.isTail)
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否可炉头" prop="isHead">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.isHead"
              placeholder="请选择是否可炉头"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('YesNo')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName("YesNo", formData.isHead)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="自动研磨设备" prop="remarks">
            <el-select
              v-if="!props.isReadonly"
              v-model="equipInfoList"
              placeholder="请选择自动研磨设备"
              clearable
              style="width: 300px"
              @change="changeEquipInfo"
              filterable
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="1"
            >
              <el-option
                v-for="item in equipInfoValue"
                :key="item.id"
                :label="`${item.equipCode}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.automaticGrindCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
            />

            <span style="word-wrap: break-word; width: 900px" v-else>
              {{ formData.remarks }}
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>

            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 规格信息 -->
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane label="规格信息" name="first">
          <el-row>
            <el-col :span="6">
              <el-form-item label="P/M" prop="pm">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.pm"
                  placeholder="请输入P/M"
                  clearable
                />

                <span v-else>{{ formData.pm }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="M/炉" prop="mf">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.mfurnace"
                  placeholder="请输入M/炉"
                  clearable
                />

                <span v-else>{{ formData.mfurnace }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="M/包" prop="mp">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.mpackage"
                  placeholder="请输入M/包"
                  clearable
                />

                <span v-else>{{ formData.mpackage }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="包/炉" prop="bagStove">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.bagStove"
                  placeholder="请输入包/炉"
                  clearable
                />

                <span v-else>{{ formData.bagStove }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="HT/QT" prop="htqt">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.htqt"
                  placeholder="请输入HT/QT"
                  clearable
                />

                <span v-else>{{ formData.htqt }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="单重" prop="singleWeight">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.singleWeight"
                  placeholder="请输入单重"
                  clearable
                >
                  <template #append>KG</template>
                </el-input>

                <span v-else>{{ formData.singleWeight }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="模重" prop="modelWeight">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.modelWeight"
                  placeholder="请输入模重"
                  clearable
                >
                  <template #append>KG</template>
                </el-input>

                <span v-else>{{ formData.modelWeight }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="重量Kg/炉" prop="kgStove">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.kgStove"
                  placeholder="请输入重量Kg/炉"
                  clearable
                />

                <span v-else>{{ formData.kgStove }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出品率" prop="yields">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.yields"
                  placeholder="请输入出品率"
                  clearable
                >
                  <template #append>%</template>
                </el-input>

                <span v-else>{{ formData.yields }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="浇注节拍" prop="pouringCycleTime">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.pouringCycleTime"
                  placeholder="请输入浇注节拍"
                  clearable
                >
                  <template #append>秒/模</template>
                </el-input>

                <span v-else>{{ formData.pouringCycleTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="熔炼理论时长" prop="smeltDurationTime">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.smeltDurationTime"
                  placeholder="请输入熔炼理论时长"
                  clearable
                >
                  <template #append>分</template>
                </el-input>

                <span v-else>{{ formData.smeltDurationTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="浇注理论时长" prop="theoreticalDurationTime">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.theoreticalDurationTime"
                  placeholder="请输入浇注理论时长"
                  clearable
                >
                  <template #append>分</template>
                </el-input>

                <span v-else>{{ formData.theoreticalDurationTime }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="包待时长" prop="packageWaitingTime">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.packageWaitingTime"
                  placeholder="请输入包待时长"
                  clearable
                >
                  <template #append>分</template>
                </el-input>

                <span v-else>{{ formData.packageWaitingTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="炉待" prop="furnaceWaitingTime">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.furnaceWaitingTime"
                  placeholder="请输入炉待"
                  clearable
                >
                  <template #append>分</template>
                </el-input>

                <span v-else>{{ formData.furnaceWaitingTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生产周期" prop="productionCycle">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.productionCycle"
                  placeholder="请输入生产周期"
                  clearable
                >
                  <template #append>天</template>
                </el-input>

                <span v-else>{{ formData.productionCycle }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="挂抛数量" prop="quantityPerHanger">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.quantityPerHanger"
                  placeholder="请输入挂抛数量"
                  clearable
                >
                  <template #append>件/挂</template>
                </el-input>

                <span v-else>{{ formData.quantityPerHanger }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="挂抛" prop="hangingThrowingNum">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.hangingThrowingNum"
                  placeholder="请输入挂抛次数"
                  clearable
                >
                  <template #append>次数</template>
                </el-input>

                <span v-else>{{ formData.hangingThrowingNum }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="滚抛" prop="rollThrowingNum">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.rollThrowingNum"
                  placeholder="请输入滚抛件/次"
                  clearable
                >
                  <template #append>件/次</template>
                </el-input>

                <span v-else>{{ formData.rollThrowingNum }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="终检效率" prop="inspectEfficiency">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.inspectEfficiency"
                  placeholder="请输入终检效率"
                  clearable
                >
                  <template #append>件/小时</template>
                </el-input>

                <span v-else>{{ formData.inspectEfficiency }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="终检节拍" prop="inspectBeat">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.inspectBeat"
                  placeholder="请输入终检节拍"
                  clearable
                >
                  <template #append>秒/小时</template>
                </el-input>

                <span v-else>{{ formData.inspectBeat }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="X光效率" prop="xefficiency">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.xefficiency"
                  placeholder="请输入X光效率"
                  clearable
                >
                  <template #append>秒/次</template>
                </el-input>

                <span v-else>{{ formData.xefficiency }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="X光检验频率" prop="xfrequency">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.xfrequency"
                  placeholder="请输入X光检验频率"
                  clearable
                >
                  <template #append>M/炉</template>
                </el-input>

                <span v-else>{{ formData.xfrequency }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="磁粉检验频率" prop="powderFrequency">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.powderFrequency"
                  placeholder="请输入磁粉检验频率"
                  clearable
                >
                  <template #append>M/炉</template>
                </el-input>

                <span v-else>{{ formData.powderFrequency }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>

      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <el-form-item
            label="创建时间"
            v-if="props.isReadonly"
            prop="createTime"
          >
            <span>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="props.isReadonly" label="创建人">
            <span>{{ formData.createdUserName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="修改时间"
            v-if="props.isReadonly"
            prop="lastUpdateTime"
          >
            <span>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="修改人"
            v-if="props.isReadonly"
            prop="lastUpdatedUserName"
          >
            <span>{{ formData.lastUpdatedUserName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useDictionary } from "@/utils/useTable";

defineOptions({
  name: "MDMMDMMATERIALADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  rulesValue: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const rules = reactive({
  materialCode: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入物料编号",
      trigger: "blur",
    },
    {
      required: true,
      message: "请输入物料名称",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],

  materialName: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入物料名称",
      trigger: "blur",
    },
    {
      required: true,
      message: "请输入物料名称",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  figureNumber: [
    {
      pattern: "[^ \x20]+",
      message: "请输入图号",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialGroupId: [
    { required: true, message: "请输入物料组", trigger: "change" },
  ],
  materialType: [
    { required: true, message: "请输入物料类型", trigger: "change" },
  ],
  shortCode: [
    {
      pattern: "[^ \x20]+",
      message: "请输入短号",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantCode: [{ required: true, message: "请输入工厂编号", trigger: "change" }],
  srcCode: [
    {
      pattern: "[^ \x20]+",
      message: "请输入外来编号",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lcCkd: [{ message: "请输入国产件标识", trigger: "change" }],
  materialState: [
    { required: true, message: "请输入物料状态", trigger: "change" },
  ],
  packageType: [
    { required: true, message: "请输入包装物料类别", trigger: "change" },
  ],
  handlingUnitType: [{ message: "请输入包装单位类别", trigger: "change" }],
  ownAssets: [{ message: "请输入是否自有资产", trigger: "change" }],
  materialSpecification: [
    {
      pattern: "[^ \x20]+",
      message: "请输入物料名称",
      trigger: "blur",
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  unit: [{ required: true, message: "请输入计量单位", trigger: "change" }],
  pm: [
    { validator: validateMust, trigger: ["blur", "change"] },
    { validator: validateDegree, trigger: "blur" },
  ],
  singleWeight: [{ validator: validateBigDecimalDegree, trigger: "blur" }],
  modelWeight: [{ validator: validateBigDecimalDegree, trigger: "blur" }],
  kgStove: [{ validator: validateBigDecimalDegree, trigger: "blur" }],
  yields: [{ validator: validateBigDecimalDegree, trigger: "blur" }],
  pouringCycleTime: [{ validator: validateBigDecimalDegree, trigger: "blur" }],
  mf: [
    { validator: validateMust, trigger: ["blur", "change"] },
    { validator: validateDegree, trigger: "blur" },
  ],
  mp: [
    { validator: validateMust, trigger: ["blur", "change"] },
    { validator: validateDegree, trigger: "blur" },
  ],
  bagStove: [
    { validator: validateMust, trigger: ["blur", "change"] },
    { validator: validateDegree, trigger: "blur" },
  ],
  smeltDurationTime: [{ validator: validateDegree, trigger: "blur" }],
  theoreticalDurationTime: [{ validator: validateDegree, trigger: "blur" }],
  packageWaitingTime: [{ validator: validateDegree, trigger: "blur" }],
  furnaceWaitingTime: [{ validator: validateDegree, trigger: "blur" }],
  productionCycle: [{ validator: validateDegree, trigger: "blur" }],
  quantityPerHanger: [{ validator: validateDegree, trigger: "blur" }],
  hangingThrowingNum: [{ validator: validateDegree, trigger: "blur" }],
  rollThrowingNum: [{ validator: validateDegree, trigger: "blur" }],
  powderFrequency: [{ validator: validateDegree, trigger: "blur" }],
  xfrequency: [{ validator: validateDegree, trigger: "blur" }],
  xefficiency: [{ validator: validateDegree, trigger: "blur" }],
  inspectBeat: [{ validator: validateDegree, trigger: "blur" }],
  inspectEfficiency: [{ validator: validateDegree, trigger: "blur" }],
  enabled: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback();
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的数字"));
  } else {
    callback();
  }
}
function validateMust(rule, value) {
  if (
    formData.materialGroupName == "产品" &&
    !/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)
  ) {
    return Promise.reject("请输入数字");
  }
  return Promise.resolve();
}
function validateBigDecimalDegree(
  rule: any,
  value: any,
  callback: (a?: any) => {}
) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback();
  } else if (!/^(?!0(\.0+)?$)\d+(\.\d{1,6})?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的数字"));
  } else {
    callback();
  }
}

const materialGroup = ref("");
const materialGroupChange = (id: any) => {
  for (let i = 0; i < mdmmatgroup.value.length; i++) {
    if (mdmmatgroup.value[i].id == id) {
      materialGroup.value = mdmmatgroup.value[i].materialGroupName;
    }
  }
};

const plantListLable = ref("");
const plant = (code: any) => {
  for (let i = 0; i < plantList.value.length; i++) {
    if (plantList.value[i].organizationCode == code) {
      plantListLable.value = plantList.value[i].organizationName;
    }
  }
};

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  materialCode: "",
  materialName: "",
  figureNumber: "",
  materialGroupId: "",
  materialGroupName: "",
  materialType: "",
  materialClassification: "",
  shortCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  srcCode: "",
  lcCkd: "",
  materialState: "",
  packageType: "",
  handlingUnitType: "",
  ownAssets: "",
  materialSpecification: "",
  unit: "",
  length: "",
  width: "",
  height: "",
  cubage: "",
  kgStove: "",
  yields: "",
  basalArea: "",
  volume: "",
  roughWeight: "",
  netWeight: "",
  nationalStandard: "",
  htqt: "",
  pm: "",
  singleWeight: "",
  modelWeight: "",
  pouringCycleTime: "",
  mf: "",
  mp: "",
  mfurnace: "",
  mpackage: "",
  bagStove: "",
  smeltDurationTime: "",
  theoreticalDurationTime: "",
  packageWaitingTime: "",
  furnaceWaitingTime: "",
  productionCycle: "",
  quantityPerHanger: "",
  isHead: "",
  isTail: "",
  hangingThrowingNum: "",
  rollThrowingNum: "",
  automaticGrindId: "",
  automaticGrindCode: "",
  automaticGrindName: "",
  enabled: 1,
  remarks: "",
  version: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  powderFrequency: "",
  xfrequency: "",
  xefficiency: "",
  inspectBeat: "",
  inspectEfficiency: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        materialCode,
        materialName,
        figureNumber,
        materialGroupId,
        materialType,
        materialClassification,
        shortCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        srcCode,
        lcCkd,
        materialState,
        packageType,
        handlingUnitType,
        ownAssets,
        materialSpecification,
        unit,
        length,
        width,
        height,
        cubage,
        basalArea,
        volume,
        roughWeight,
        netWeight,
        nationalStandard,
        htqt,
        pm,
        singleWeight,
        modelWeight,
        kgStove,
        yields,
        pouringCycleTime,
        mf,
        mp,
        mfurnace,
        mpackage,
        bagStove,
        smeltDurationTime,
        theoreticalDurationTime,
        packageWaitingTime,
        furnaceWaitingTime,
        productionCycle,
        quantityPerHanger,
        isHead,
        isTail,
        hangingThrowingNum,
        rollThrowingNum,
        automaticGrindId,
        enabled,
        remarks,
        version,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        powderFrequency,
        xfrequency,
        xefficiency,
        inspectBeat,
        inspectEfficiency,
      } = newVal;
      Object.assign(formData, {
        id,
        materialCode,
        materialName,
        figureNumber,
        materialGroupId,
        materialType,
        materialClassification,
        shortCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        srcCode,
        lcCkd,
        materialState,
        packageType,
        handlingUnitType,
        ownAssets,
        materialSpecification,
        unit,
        length,
        width,
        height,
        cubage,
        basalArea,
        volume,
        roughWeight,
        netWeight,
        nationalStandard,
        htqt,
        pm,
        singleWeight,
        modelWeight,
        kgStove,
        yields,
        pouringCycleTime,
        mf,
        mp,
        mfurnace,
        mpackage,
        bagStove,
        smeltDurationTime,
        theoreticalDurationTime,
        packageWaitingTime,
        furnaceWaitingTime,
        productionCycle,
        quantityPerHanger,
        isHead,
        isTail,
        hangingThrowingNum,
        rollThrowingNum,
        automaticGrindId,
        enabled,
        remarks,
        version,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        powderFrequency,
        xfrequency,
        xefficiency,
        inspectBeat,
        inspectEfficiency,
      });
      formData.materialType =
        newVal.materialType == null ? "" : String(formData.materialType);
      formData.unit = newVal.unit == null ? "" : String(formData.unit);
      formData.materialState =
        newVal.materialState == null ? "" : String(formData.materialState);
      formData.materialClassification =
        newVal.materialClassification == null
          ? ""
          : String(formData.materialClassification);
      formData.mp = newVal.mp == null ? "" : String(newVal.mpackage);
      formData.mf = newVal.mf == null ? "" : String(newVal.mfurnace);
      formData.isHead = newVal.isHead == null ? "" : String(newVal.isHead);
      formData.isTail = newVal.isTail == null ? "" : String(newVal.isTail);
      materialGroupChange(formData.materialGroupId);
      plant(formData.plantCode);
      getMdmmatgroup();
      if (newVal.automaticGrindId) {
        equipInfoList.value = newVal.automaticGrindId.split(",");
      }
      equipInfos();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.figureNumber = "";
  formData.materialGroupId = "";
  formData.materialType = "";
  formData.materialClassification = "";
  formData.shortCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.srcCode = "";
  formData.lcCkd = "";
  formData.materialState = "";
  formData.packageType = "";
  formData.handlingUnitType = "";
  formData.ownAssets = "";
  formData.materialSpecification = "";
  formData.unit = "";
  formData.length = "";
  formData.width = "";
  formData.height = "";
  formData.cubage = "";
  formData.basalArea = "";
  formData.volume = "";
  formData.roughWeight = "";
  formData.netWeight = "";
  formData.nationalStandard = "";
  formData.htqt = "";
  formData.pm = "";
  formData.singleWeight = "";
  formData.modelWeight = "";
  formData.kgStove = "";
  formData.yields = "";
  formData.pouringCycleTime = "";
  formData.mf = "";
  formData.mp = "";
  formData.mfurnace = "";
  formData.mpackage = "";
  formData.bagStove = "";
  formData.smeltDurationTime = "";
  formData.theoreticalDurationTime = "";
  formData.packageWaitingTime = "";
  formData.furnaceWaitingTime = "";
  formData.productionCycle = "";
  formData.quantityPerHanger = "";
  formData.isHead = "";
  formData.isTail = "";
  formData.hangingThrowingNum = "";
  formData.rollThrowingNum = "";
  formData.automaticGrindId = "";
  formData.automaticGrindCode = "";
  formData.automaticGrindName = "";
  formData.enabled = 1;
  formData.remarks = "";
  formData.version = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.powderFrequency, (formData.xfrequency = "");
  formData.xefficiency = "";
  formData.inspectBeat = "";
  formData.inspectEfficiency = "";
  equipInfoList.value = [];
}
// 一开始展示基本数据
const activeName = ref("first");

const loading = ref(false);

/** 物料主数据保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      for (let i = 0; i < plantList.value.length; i++) {
        if (plantList.value[i].organizationCode == formData.plantCode) {
          formData.plantId = plantList.value[i].id;
        }
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmmaterial/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
const plantList: any = ref([]);
const mdmmatgroup: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};

const getMdmmatgroup = async () => {
  if (formData.plantCode != "") {
    for (let i = 0; i < plantList.value.length; i++) {
      if (plantList.value[i].organizationCode == formData.plantCode) {
        formData.plantId = plantList.value[i].id;
      }
    }

    const res2 = await request({
      url: `/mdm/mdmmatgroup/getList`,
      method: "post",
      data: { plantId: formData.plantId },
    });

    mdmmatgroup.value = res2.data;
  } else {
    formData.materialGroupId = "";
    mdmmatgroup.value = [];
  }
};

// 输入框出发时
const changePlant = () => {
  getMdmmatgroup();
  equipInfos();
};
onMounted(() => {
  getPlantList();
});
function changeMaterialGroup(id) {
  if (id) {
    mdmmatgroup.value.forEach((item) => {
      if (item.id == id) {
        formData.materialGroupName = item.materialGroupName;
      }
    });
  }
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
//自动研磨设备赋值
const equipInfoList = ref([]);
const changeEquipInfo = (id: any) => {
  formData.automaticGrindId = equipInfoList.value.join(",");
  let equipInfoCodeList = [];
  let equipInfoNameList = [];
  // let materialNameList = [];
  equipInfoList.value.forEach((item: any) => {
    equipInfoValue.value.forEach((i) => {
      if (item === i.id) {
        equipInfoCodeList.push(i.equipCode);
        equipInfoNameList.push(i.equipName);
      }
    });
  });
  formData.automaticGrindCode = equipInfoCodeList.join(",");
  formData.automaticGrindName = equipInfoNameList.join(",");
};
const equipInfoValue: any = ref([]);
const equipInfos = async () => {
  if (formData.plantCode != "") {
    const res2: any = await request({
      url: `/mdm/mdmequipinfo/getList`,
      method: "post",
      data: { plantId: formData.plantId, equipTypeCode: "自动研磨" },
    });
    equipInfoValue.value = res2.data;
  } else {
    equipInfoValue.value = [];
  }
};
</script>
<style scoped lang="scss">
.right-input {
  :deep(.el-input__inner) {
    text-align: right;
    padding-right: 20px;
  }

  :deep(.el-input__inner::placeholder) {
    text-align: right;
  }

  :deep(.el-form-item__error) {
    right: 0px !important;
  }
}
.word {
  word-wrap: break-word;
  width: 200px; /* 设置容器宽度 */
}
</style>
